package com.yugao.fintech.antelope.base.datasource;

import com.yugao.fintech.antelope.base.datasource.mapper.CommonMapper;
import com.yugao.fintech.antelope.base.model.constants.TenantCons;
import com.yugao.fintech.antelope.base.model.constants.UserCons;
import com.yugao.fintech.antelope.base.model.module.tenant.TenantContextHolder;
import com.yugao.fintech.antelope.base.tenant.core.TenantConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Service
public class CommonService {
    @Autowired
    private TenantConfig tenantConfig;
    @Autowired
    private CommonMapper commonMapper;

    private static final Map<String, Boolean> dbTableName = new ConcurrentHashMap<>();

    /**
     * 检查表是否存在, 目前不支持多数据源
     */
    public boolean checkTableExists(String tableName) {
        try {
            Boolean isExist = dbTableName.get(tableName);
            if (Objects.nonNull(isExist)) {
                return isExist;
            }
            boolean ret = commonMapper.checkTableExists(tableName) > 0;
            dbTableName.put(tableName, ret);
            return ret;
        } catch (Exception e) {
            log.error("检查表是否存在失败", e);
        }
        return false;
    }

    /**
     * 删除数据
     */
    public void deleteAllDataByUserId(Long userId) {
        if (Objects.isNull(userId) || UserCons.ADMIN_ID.compareTo(userId) == 0) {
            return;
        }

        TenantContextHolder.get().filterTenant(false);

        for (String tableName : tenantConfig.getAssociatedUserTables()) {
            if (!checkTableExists(tableName)) {
                continue;
            }
            log.info("delete user data start ===> userId: {}, tableName: {}", userId, tableName);
            Integer count = commonMapper.deleteAllDataByUserId(tableName, userId);
            log.info("delete user data end ===> userId: {}, tableName: {}, size: {}", userId, tableName, count);
        }
    }

    /**
     * 删除数据
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteAllDataByTenantId(Long tenantId) {
        if (Objects.isNull(tenantId) || TenantCons.SYSTEM_TENANT_ID.compareTo(tenantId) == 0) {
            return;
        }

        TenantContextHolder.get().filterTenant(false);

        for (String tableName : tenantConfig.getHasTenantIdTables()) {
            if (!checkTableExists(tableName)) {
                continue;
            }
            log.info("delete tenant data start ===> tenantId: {}, tableName: {}", tenantId, tableName);

            Integer count = commonMapper.deleteAllDataByTenantId(tableName, tenantId);
            log.info("delete tenant data end ===> tenantId: {}, tableName: {}, size: {}", tenantId, tableName, count);
        }
    }
}
